package com.example.myapplication.Adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.myapplication.Model.TodoModel
import com.example.myapplication.R

class TodoAdapter(
    private var todoList: MutableList<TodoModel>,
    private val onItemClickListener: OnItemClickListener
) : RecyclerView.Adapter<TodoAdapter.TodoViewHolder>() {

    interface OnItemClickListener {
        fun onItemDelete(todo: TodoModel)
        fun onItemEdit(todo: TodoModel)
        fun onItemComplete(todo: TodoModel, isCompleted: Boolean)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo, parent, false)
        return TodoViewHolder(view)
    }

    override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
        val todo = todoList[position]
        holder.bind(todo)
    }

    override fun getItemCount(): Int {
        return todoList.size
    }

    inner class TodoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val titleTextView: TextView = itemView.findViewById(R.id.title_text_view)
        private val descriptionTextView: TextView = itemView.findViewById(R.id.description_text_view)
        private val completedCheckBox: CheckBox = itemView.findViewById(R.id.completed_check_box)
        private val editButton: View = itemView.findViewById(R.id.edit_button)
        private val deleteButton: View = itemView.findViewById(R.id.delete_button)

        fun bind(todo: TodoModel) {
            titleTextView.text = todo.title
            descriptionTextView.text = todo.description
            completedCheckBox.isChecked = todo.isCompleted

            completedCheckBox.setOnCheckedChangeListener { _, isChecked ->
                todo.isCompleted = isChecked
                onItemClickListener.onItemComplete(todo, isChecked)
            }

            editButton.setOnClickListener {
                onItemClickListener.onItemEdit(todo)
            }

            deleteButton.setOnClickListener {
                onItemClickListener.onItemDelete(todo)
            }
        }
    }
}